import axios from"axios"
import app from "../main"


axios.defaults.withCredentials = true;

const instance=axios.create({
    baseURL:"http://127.0.0.1:9191",
    timeout:5000,
    withCredentials:true   // 允许跨域带上cookies
})

//状态检查函数
function checkStatus (response) {
    const status = response.status;
    if ((status >= 200 && status < 300) || status === 304) {
      return response.data;
    } else {
      let errorInfo = '';
      switch (status) {
        case 400:
          errorInfo = '400：错误请求';
          break;
        case 401:
          errorInfo = '401：访问令牌无效或已过期';
          break;
        case 403:
          errorInfo = '403：拒绝访问';
          break;
        case 404:
          errorInfo = '404：资源不存在';
          break;
        case 405:
          errorInfo = '405：请求方法未允许'
          break;
        case 408:
          errorInfo = '408：请求超时'
          break;
        case 500:
          errorInfo = '500：访问服务失败';
          break;
        case 501:
          errorInfo = '501：未实现';
          break;
        case 502:
          errorInfo = '502：无效网关';
          break;
        case 503:
          errorInfo = '503：服务不可用'
          break;
        default:
          errorInfo = `连接错误`
      }
      return {
        status,
        errmsg: errorInfo
      }
    }
  }


//请求拦截器
instance.interceptors.request.use(config=>{
  // console.log(config)
    return config
},err=>{
    return Promise.reject(err)
})

//响应拦截器
instance.interceptors.response.use(response=>{
    let result=checkStatus(response)
    if(result.errmsg){
        app.$message({
            type:"warning",
            message:result.msg,
            center:true
        })
    }else{
        // if(result.code!=0){
        //   app.$message({
        //     type:"error",
        //     message:result.msg,
        //     center:true
        // })
        // }else{
          return result
        // }
    }
},err=>{
    return Promise.reject(err)
})


export default instance
